package com.tmxk.employee.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

/**
 * 短信发送模板
 */
public class SendSms {
    private static Logger logger = Logger.getLogger(SendSms.class);
    private static final String ACCESS_KEY_ID = "LTAI5t6cbj4RuTGAsYfd2KGp";
    private static final String ACCESS_KEY_SECRET = "30x3JvilD1J5mP3nGjDTVsXKtubeD8";
    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     * 使用STS鉴权方式初始化账号Client，推荐此方式。本示例默认使用AK&SK方式。
     * @param accessKeyId
     * @param accessKeySecret
     * @param securityToken
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClientWithSTS(String accessKeyId, String accessKeySecret, String securityToken) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret)
                // 必填，您的 Security Token
                .setSecurityToken(securityToken)
                // 必填，表明使用 STS 方式
                .setType("sts");
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     * 短信发送接口
     * @return
     */
    public static boolean sendSms01(String phoneNumber) {
        //定义一个标识符,用来判断当前验证是否发送成功
        boolean isSendSuccess = true;
        try{
            //创建客户端通信连接
            Client client = SendSms.createClient(ACCESS_KEY_ID,ACCESS_KEY_SECRET);
            //创建消息发送请求
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            // 签名验证
            sendSmsRequest.setSignName("阿里云短信测试");
            //模版Code
            sendSmsRequest.setTemplateCode("SMS_154950909");
            //手机号
            sendSmsRequest.setPhoneNumbers(phoneNumber);
            //发送的信息模板  验证码
            //创建Map集合对象,用来存储随机生成的验证码
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code",RandomNumberUtils.getFourNum());
            sendSmsRequest.setTemplateParam(jsonObject.toJSONString());
            // 调用短信发送api接口,并响应结果
            //  SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest,new RuntimeOptions());
            //   logger.info(sendSmsResponse);
            // 控制台打印具体返回字符串信息
            //   com.aliyun.teaconsole.Client.log(Common.toJSONString(sendSmsResponse));
            //获取短信发送后的请求状态码值
            //    isSendSuccess = "OK".equals(sendSmsResponse.getBody().getCode()) ? true : false;
        }catch (Exception e){
            e.printStackTrace();
        }
        return isSendSuccess;
    }

    /**
     * 短信发送接口
     * @return
     */
    public static Map<String,Object> sendSms(String phoneNumber) {
        //创建Map集合对象
        Map<String,Object> map = new HashMap<>();
        //定义一个标识符,用来判断当前验证是否发送成功
        boolean isSendSuccess = true;
        //验证码
        String verifyCode = RandomNumberUtils.getFourNum();
        try{
            //创建客户端通信连接
            Client client = SendSms.createClient(ACCESS_KEY_ID,ACCESS_KEY_SECRET);
            //创建消息发送请求
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            // 签名验证
            sendSmsRequest.setSignName("阿里云短信测试");
            //模版Code
            sendSmsRequest.setTemplateCode("SMS_154950909");
            //手机号
            sendSmsRequest.setPhoneNumbers(phoneNumber);
            //发送的信息模板  验证码
            //创建Map集合对象,用来存储随机生成的验证码
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code",verifyCode);
            sendSmsRequest.setTemplateParam(jsonObject.toJSONString());
            // 调用短信发送api接口,并响应结果
            //  SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest,new RuntimeOptions());
            //   logger.info(sendSmsResponse);
            // 控制台打印具体返回字符串信息
            //   com.aliyun.teaconsole.Client.log(Common.toJSONString(sendSmsResponse));
            //获取短信发送后的请求状态码值
            //    isSendSuccess = "OK".equals(sendSmsResponse.getBody().getCode()) ? true : false;
        }catch (Exception e){
            e.printStackTrace();
        }
        if(isSendSuccess){
            map.put("verifyCode",verifyCode);
        }
        map.put("isSendSuccess",isSendSuccess);
        return map;
    }


    public static void main(String[] args_) throws Exception {
        // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，
        // 更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
        /*com.aliyun.dysmsapi20170525.Client client = SendSms.createClient("ACCESS_KEY_ID", "ACCESS_KEY_SECRET");
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setPhoneNumbers("18761647399")
                .setTemplateParam("{\"code\":\"1234\"}");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        com.aliyun.dysmsapi20170525.models.SendSmsResponse resp = client.sendSmsWithOptions(sendSmsRequest, runtime);
        com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(resp));*/

        System.out.println(sendSms("18761647399"));
    }
}
